<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><%= title %></title>
  <link rel="stylesheet" href="/css/style.css">
  <style>
    .status-bar {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 15px;
      margin-bottom: 20px;
      border-radius: 8px;
      text-align: center;
    }
    .status-item {
      display: inline-block;
      margin: 0 15px;
    }
    .status-item strong {
      display: block;
      font-size: 1.1em;
    }
    .update-btn {
      background: #28a745;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 5px;
      cursor: pointer;
      font-size: 16px;
      margin: 10px;
    }
    .update-btn:hover {
      background: #218838;
    }
    .update-btn:disabled {
      background: #6c757d;
      cursor: not-allowed;
    }
    .warning-box {
      background: #fff3cd;
      border: 1px solid #ffeaa7;
      color: #856404;
      padding: 15px;
      border-radius: 5px;
      margin-bottom: 20px;
    }
    .info-box {
      background: #d1ecf1;
      border: 1px solid #bee5eb;
      color: #0c5460;
      padding: 15px;
      border-radius: 5px;
      margin-bottom: 20px;
    }
    .trading-status {
      display: inline-block;
      padding: 5px 10px;
      border-radius: 15px;
      font-weight: bold;
      font-size: 0.9em;
    }
    .trading-status.active {
      background: #d4edda;
      color: #155724;
    }
    .trading-status.inactive {
      background: #f8d7da;
      color: #721c24;
    }
    .auto-refresh {
      text-align: center;
      margin: 20px 0;
    }
    .refresh-indicator {
      display: inline-block;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      margin-right: 5px;
    }
    .refresh-indicator.active {
      background: #28a745;
      animation: pulse 1s infinite;
    }
    .refresh-indicator.inactive {
      background: #dc3545;
    }
    @keyframes pulse {
      0% { opacity: 1; }
      50% { opacity: 0.5; }
      100% { opacity: 1; }
    }
  </style>
</head>
<body>
  <div class="container">
    <header>
      <h1>📈 <%= title %></h1>
    </header>
    
    <div class="warning-box">
      <strong>⚠️ 临时模式运行中</strong><br>
      数据库连接问题，当前使用临时模式。股票数据实时获取但不保存到数据库。
      <br><strong>解决方案:</strong> 请查看 <code>fix-database.md</code> 文件获取详细的数据库修复指南。
    </div>
    
    <div class="status-bar">
      <div class="status-item">
        <strong id="current-time">--:--:--</strong>
        <span>当前时间</span>
      </div>
      <div class="status-item">
        <span id="trading-status" class="trading-status inactive">检查中...</span>
      </div>
      <div class="status-item">
        <strong id="last-update"><%= lastUpdateTime %></strong>
        <span>最后更新</span>
      </div>
      <div class="status-item">
        <span class="refresh-indicator inactive" id="refresh-indicator"></span>
        <span id="refresh-status">手动模式</span>
      </div>
    </div>
    
    <div class="auto-refresh">
      <button class="update-btn" onclick="manualUpdate()" id="update-btn">
        🔄 手动更新数据
      </button>
      <button class="update-btn" onclick="toggleAutoRefresh()" id="auto-btn">
        ⏰ 启用自动刷新
      </button>
    </div>
    
    <main>
      <section class="stock-list">
        <h2>📊 股票列表</h2>
        <div class="stock-cards" id="stock-list">
          <div class="loading">正在加载股票数据...</div>
        </div>
      </section>
    </main>
    
    <footer>
      <div class="info-box">
        <strong>💡 使用说明:</strong><br>
        • 点击"手动更新数据"获取最新股票价格<br>
        • 启用自动刷新后，在交易时间内会每30秒自动更新<br>
        • 交易时间: 周一至周五 09:29-15:00<br>
        • 数据库修复后请使用完整版本: <code>node app.js</code>
      </div>
      <p>&copy; 2023 股票监控系统 - 临时版本</p>
    </footer>
  </div>
  
  <script>
    let autoRefreshEnabled = false;
    let autoRefreshInterval = null;
    
    // 更新当前时间
    function updateCurrentTime() {
      const now = new Date();
      document.getElementById('current-time').textContent = 
        now.toLocaleTimeString('zh-CN');
    }
    
    // 检查交易状态
    async function checkTradingStatus() {
      try {
        const response = await fetch('/api/trading-status');
        const data = await response.json();
        
        const statusElement = document.getElementById('trading-status');
        if (data.isTradingTime) {
          statusElement.textContent = '✅ 交易中';
          statusElement.className = 'trading-status active';
        } else {
          statusElement.textContent = '❌ 非交易时间';
          statusElement.className = 'trading-status inactive';
        }
        
        if (data.lastUpdateTime) {
          document.getElementById('last-update').textContent = data.lastUpdateTime;
        }
      } catch (error) {
        console.error('检查交易状态失败:', error);
      }
    }
    
    // 获取股票数据
    async function fetchStocks() {
      const stockList = document.getElementById('stock-list');
      
      try {
        const response = await fetch('/api/stocks');
        const stocks = await response.json();
        
        if (stocks.length === 0) {
          stockList.innerHTML = '<div class="no-stocks">暂无股票数据，请点击更新按钮</div>';
          return;
        }
        
        let html = '';
        for (const stock of stocks) {
          const priceChange = stock.price - stock.openPrice;
          const priceChangePercent = ((priceChange / stock.openPrice) * 100).toFixed(2);
          const changeClass = priceChange >= 0 ? 'up' : 'down';
          const changeSymbol = priceChange >= 0 ? '↗' : '↘';
          
          html += `
            <div class="stock-card">
              <div class="stock-header">
                <h3>${stock.name}</h3>
                <span class="stock-code">${stock.code}</span>
              </div>
              <div class="price-info">
                <div class="current-price">
                  <span class="value ${changeClass}">¥${stock.price.toFixed(2)}</span>
                </div>
                <div class="price-change">
                  <span class="value ${changeClass}">
                    ${changeSymbol} ¥${priceChange.toFixed(2)} (${priceChangePercent}%)
                  </span>
                </div>
              </div>
              <div class="price-details">
                <div class="detail-item">
                  <span class="label">开盘:</span>
                  <span class="value">¥${stock.openPrice.toFixed(2)}</span>
                </div>
                <div class="detail-item">
                  <span class="label">最高:</span>
                  <span class="value up">¥${stock.highPrice.toFixed(2)}</span>
                </div>
                <div class="detail-item">
                  <span class="label">最低:</span>
                  <span class="value down">¥${stock.lowPrice.toFixed(2)}</span>
                </div>
                <div class="detail-item">
                  <span class="label">更新:</span>
                  <span class="value">${new Date(stock.timestamp).toLocaleTimeString('zh-CN')}</span>
                </div>
              </div>
            </div>
          `;
        }
        
        stockList.innerHTML = html;
      } catch (error) {
        console.error('获取股票数据失败:', error);
        stockList.innerHTML = '<div class="error">获取股票数据失败，请稍后重试</div>';
      }
    }
    
    // 手动更新
    async function manualUpdate() {
      const btn = document.getElementById('update-btn');
      btn.disabled = true;
      btn.textContent = '🔄 更新中...';
      
      try {
        const response = await fetch('/api/update', { method: 'POST' });
        const result = await response.json();
        
        if (response.ok) {
          await fetchStocks();
          await checkTradingStatus();
          console.log('更新成功:', result.message);
        } else {
          throw new Error(result.error);
        }
      } catch (error) {
        console.error('更新失败:', error);
        alert('更新失败: ' + error.message);
      } finally {
        btn.disabled = false;
        btn.textContent = '🔄 手动更新数据';
      }
    }
    
    // 切换自动刷新
    function toggleAutoRefresh() {
      const btn = document.getElementById('auto-btn');
      const indicator = document.getElementById('refresh-indicator');
      const status = document.getElementById('refresh-status');
      
      if (autoRefreshEnabled) {
        // 停止自动刷新
        autoRefreshEnabled = false;
        if (autoRefreshInterval) {
          clearInterval(autoRefreshInterval);
          autoRefreshInterval = null;
        }
        btn.textContent = '⏰ 启用自动刷新';
        indicator.className = 'refresh-indicator inactive';
        status.textContent = '手动模式';
      } else {
        // 启动自动刷新
        autoRefreshEnabled = true;
        autoRefreshInterval = setInterval(async () => {
          // 检查是否在交易时间内
          const response = await fetch('/api/trading-status');
          const data = await response.json();
          
          if (data.isTradingTime) {
            await fetchStocks();
          }
        }, 30000); // 30秒
        
        btn.textContent = '⏸️ 停止自动刷新';
        indicator.className = 'refresh-indicator active';
        status.textContent = '自动模式 (30s)';
      }
    }
    
    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', () => {
      updateCurrentTime();
      checkTradingStatus();
      fetchStocks();
      
      // 每秒更新时间
      setInterval(updateCurrentTime, 1000);
      
      // 每分钟检查交易状态
      setInterval(checkTradingStatus, 60000);
    });
  </script>
</body>
</html>